package com.example.autopia.view.Activities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import com.example.autopia.databinding.ActivityThemeBinding
import com.example.autopia.utilities.PreferenceManager

class ThemeActivity : AppCompatActivity() {
    private lateinit var binding: ActivityThemeBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityThemeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val themePreference: PreferenceManager = PreferenceManager(this@ThemeActivity)
        when (themePreference.getString("theme")) {
            null, "system" -> {
                binding.cbSystem.isChecked = true
            }
            "dark" -> {
                binding.cbDarkTheme.isChecked = true
            }
            else -> {
                binding.cbLightTheme.isChecked = true
            }
        }

        binding.apply {
            cbLightTheme.setOnClickListener {
                if (cbLightTheme.isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                    themePreference.putString("theme", "light")
                    cbDarkTheme.isChecked = false
                    cbSystem.isChecked = false
                } else {
                    cbLightTheme.isChecked = true
                }
            }

            cbDarkTheme.setOnClickListener {
                if (cbDarkTheme.isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                    themePreference.putString("theme", "dark")
                    cbLightTheme.isChecked = false
                    cbSystem.isChecked = false
                } else {
                    cbDarkTheme.isChecked = true
                }
            }

            cbSystem.setOnClickListener {
                if (cbSystem.isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
                    themePreference.putString("theme", "system")
                    cbLightTheme.isChecked = false
                    cbDarkTheme.isChecked = false
                } else {
                    cbSystem.isChecked = true
                }
            }
        }

        binding.btBack.setOnClickListener {
            finish()
        }
    }
}